

/*
本插件为配合Kugar.AdminLTE控件框架使用的表格功能,主要提供了左右两侧固定列,排序按钮功能
用于取代jqTable,由于jqTable过于复杂,列宽等不容配置,因此单独编写了这个控件,用于实现部分常用的表格功能

调用的方式:
      $("#testtb").simpleTable({
        leftFloatCol: parseInt($("#testtb").data("leftfloat")),    //左侧浮动n列,默认为0
        rightFloatCol: parseInt($("#testtb").data("rightfloat")),  //右侧浮动n列,,默认为0
        scrollY:false,                                             //是否使用高度固定的滚动条功能
        scrollHeight:0,                                            //固定的高度,单位为px,默认为0,只能是数字
      }).on("webui_table.sort",function(e,data){  
        //点击刷新按钮触发的事件data为事件内容  data.sortType 为修改后的排序方式: asc,desc,unsort 三种   data.sortKey 为排序列的key
        //请注意在这个时间中,自行增加loading防止多次出发
        var p=0;
      })
      .on("webui_table.refresh",function(e){
        //出发刷新功能的时候,触发该事件,

      }).on("webui_table.init",function(e){
          //控件初始化完成后,触发该事件
      })
      ;

      $("#testtb").simpleTable().refresh();   //该函数用于刷新表格,重新应用表格样式
      $("#testtb").simpleTable().cleanWrap();   //该函数用于清空表格样式,还原原来的表格

*/

; (function ($) {
    $.fn.simpleTable = function (options) {
        var defaults = {
            //各种参数、各种属性
            leftFloatCol: 0,
            rightFloatCol: 0,
            scrollY: false,
            scrollHeight: 200,
            autoAddRow: false
        };


        var isInitCompleted = false;

        //options合并到defaults上,defaults继承了options上的各种属性和方法,将所有的赋值给endOptions
        var endOptions = $.extend(defaults, options);

        var $table = $($(this).first());

        if (!$table.is("table.webui_table")) {
            return null;
        }

        var obj = $table.data("webui_table_object");

        if (obj) {
            return obj;
        }

        //处理内容Y轴滚动事件
        var __onScrollYHandler = function (event) {
            var st = $(this).scrollTop();

            var tmpLeft = $(this).data("leftFloatDiv");

            if (tmpLeft) {
                tmpLeft.scrollTop(st);
            }

            var tmpRight = $(this).data("rightFloatDiv");

            if (tmpRight) {
                tmpRight.scrollTop(st);
            }
        };

        var __onSortByButtonClick = function (event) {
            //排序按钮变化的顺序为: 未排序-升序--降序-未排序
            var $this = $(this);

            var newSortType = "";

            if ($this.is(".fa-sort")) { // 未排序
                $this.removeClass("fa-sort").addClass("fa-sort-amount-asc");
                newSortType = "asc";
            }
            else if ($this.is(".fa-sort-amount-asc")) {
                $this.removeClass("fa-sort-amount-asc").addClass("fa-sort-amount-desc");
                newSortType = "desc";
            }
            else if ($this.is(".fa-sort-amount-desc")) {
                $this.removeClass("fa-sort-amount-desc").addClass("fa-sort");
                newSortType = "unsort";
            }

            event.stopPropagation();

            $table.trigger("webui_table.sort",
                {
                    sortType: newSortType,
                    sortKey: $this.data("sortkey"),
                    triggerElement: this,
                });
        };

        var __onCheckboxClickHandler = function(event) {
            

        };

        //去除table的包装元素
        this.cleanWrap = function () {
            if (!$table.is('.wraped')) {
                return this;
            }

            var wrapper = $table.closest(".webui_table_wrapper");

            $table.insertBefore(wrapper);

            wrapper.remove();

            if (isInitCompleted) {
                $table.trigger("webui_table.cleanwrapper", this);
            }

        }

        //重新组装table
        this.refresh = function () {
            console.log("table refresh");

            this.cleanWrap();

            var realTable = $table;
            var leftFloatDiv, rightFloatDiv;
            var leftFloatTable, rightFloatTable;

            if ((endOptions.scrollHeight > 0 || 
                endOptions.leftFloatCol > 0 || endOptions.rightFloatCol>0)
            ) {
                realTable.find("td .table_column_buttonlist").each(function () {
                    var w = $(this).outerWidth();
                    $(this).closest("td").width(w);
                });

                var realTableParent = $(realTable).parent();

                var outSideBox = $(
                    "<div class=\"box no-border no-margin webui_table_wrapper hidden\"><div class=\"box-body no-padding\"></div></div>"
                );
                var outSideBoxBody = $(outSideBox).children(".box-body");

                var leftFloatQty = endOptions.leftFloatCol;
                var rightFloatQty = endOptions.rightFloatCol;

                

                var leftFloatTableWidth = 0,
                    rightFloatTableWidth = 0;


                if (leftFloatQty > 0 || rightFloatQty > 0) { //如果左右需要浮动列的情况下
                    if (leftFloatQty > 0) {
                        leftFloatDiv = $("<div class=\"webui_table_float_left hidden\"><table><thead></thead></table></div>");
                        leftFloatTable = $(leftFloatDiv).children("table");
                        leftFloatTable.attr("class", realTable.attr("class"));
                        leftFloatTable.removeClass("webui_table");
                    }
                    if (rightFloatQty > 0) {
                        rightFloatDiv = $("<div class=\"webui_table_float_right hidden\"><table><thead></thead></table></div>");
                        rightFloatTable = $(rightFloatDiv).children("table");
                        rightFloatTable.attr("class", realTable.attr("class"));
                        rightFloatTable.removeClass("webui_table");
                    }

                    //循环多层表头,将表头clone到左右浮动table
                    realTable.children("thead").children("tr").each(function () { //兼容多个表头行的情况
                        var headerRowMaxHeight = 0;
                        var readTableHeadRow = $(this);
                        var realTableHeadTh = $(this).find("th");

                        //计算原始表头中,当前行的最大高度
                        realTableHeadTh.each(function () {
                            if ($(this).outerHeight() > headerRowMaxHeight) {
                                headerRowMaxHeight = $(this).outerHeight();
                            }
                        });

                        if (leftFloatQty > 0) {
                            var floatThead = leftFloatTable.find("thead").first();
                            var floatHeadRow = $(this).clone(true, true);
                            floatThead.append(floatHeadRow);

                            var currentFloatHeadTotalWidth = 0;
                            var currentMapperColSpan = 0;

                            floatHeadRow.find("th").each(function (index, e) {
                                var colspan = parseIntEx($(this).attr("colspan"), 1);
                                currentMapperColSpan += colspan;
                                if (currentMapperColSpan > leftFloatQty) {
                                    $(e).remove();
                                } else {
                                    currentFloatHeadTotalWidth += $(realTableHeadTh[index]).outerWidth();
                                    $(this).height(headerRowMaxHeight);
                                    //$(this).html($(realTableHeadTh[index]).html());
                                }

                            });

                            if (leftFloatTableWidth < currentFloatHeadTotalWidth) {
                                leftFloatTableWidth = currentFloatHeadTotalWidth;
                            }

                        }

                        if (rightFloatQty > 0) {
                            var floatThead = rightFloatTable.find("thead").first();
                            var floatHeadRow =  $(this).clone(true, true).empty();
                            floatThead.append(floatHeadRow);

                            //var thCount = realTable.children("thead").find("th").length - rightFloatQty;
                            var currentFloatHeadTotalWidth = 0;
                            //var currentMapperColSpan = 0;

                            $(this).find("th").slice(-1 * rightFloatQty).each(function (index, e) {
                                var newCell= $(e).clone(true, true);

                                floatHeadRow.append(newCell);

                                currentFloatHeadTotalWidth += newCell.outerWidth();

                                //currentMapperColSpan += parseIntEx($(this).attr("colspan"), 1);

                                //if (currentMapperColSpan <= thCount) { //删除非浮动列的表头
                                //    $(e).remove();
                                //} else {
                                //    currentFloatHeadTotalWidth += $(realTableHeadTh[index]).outerWidth();
                                //    $(this).height(headerRowMaxHeight);
                                //    //$(this).html($(realTableHeadTh[index]).html());
                                //}


                            });

                            if (rightFloatTableWidth < currentFloatHeadTotalWidth) {
                                rightFloatTableWidth = currentFloatHeadTotalWidth;
                            }
                        }
                    });

                    //开始计算左侧浮动列
                    if (leftFloatQty > 0) {

                        leftFloatTable.append("<tbody></tbody>");

                        outSideBoxBody.append(leftFloatDiv);

                        $(leftFloatTable).height($(realTable).outerHeight());
                        $(leftFloatTable).children("thead").height($(realTable).children("thead").height());
                    }

                    //开始计算右侧浮动列
                    if (rightFloatQty > 0) {

                        rightFloatTable.append("<tbody></tbody>");

                        outSideBoxBody.append(rightFloatDiv);

                        $(rightFloatTable).height($(realTable).outerHeight());
                        $(rightFloatTable).children("thead").height($(realTable).children("thead").height());
                    }
                }


                var realTableRows = $(realTable).children("tbody").children("tr");

                //开始复制左右浮动列的数据栏
                realTableRows.each(function (index, e) {
                    var row = $(e);
                    var tdlst = $(row).children("td");
                    var sourceHeight = $(e).height();

                    if (leftFloatTable) {
                        var r = $("<tr></tr>");
                        var c = 0;
                        var i = 0;
                        while (c<leftFloatQty) {
                            r.append($(tdlst[i]).clone(true, true));

                            if ($(tdlst[i]).attr("colspan")) {
                                c += $(tdlst[i]).attr("colspan");
                            } else {
                                c++;
                            }

                            i++;
                        }
                        //for (var i = 0; i < leftFloatQty; i++) {
                            

                        //}
                        r.height(sourceHeight + "px");
                        leftFloatTable.append(r);
                    }

                    if (rightFloatTable) {
                        var r = $("<tr></tr>");
                        var c = 0;
                        var i = 0;

                        //while (c < rightFloatQty) {
                        //    r.append($($(tdlst[tdlst.length - 1 - i])).clone(true, true));

                        //    if ($($(tdlst[tdlst.length - 1 - i])).attr("colspan")) {
                        //        c += $($(tdlst[tdlst.length - 1 - i])).attr("colspan");
                        //    } else {
                        //        c++;
                        //    }

                        //    i++;
                        //}

                        for (var i = rightFloatQty - 1; i >= 0; i--) {
                            r.append($(tdlst[tdlst.length - 1 - i]).clone(true, true));

                            if ($($(tdlst[tdlst.length - 1 - i])).attr("colspan")) {
                                c += $($(tdlst[tdlst.length - 1 - i])).attr("colspan");
                            } else {
                                c++;
                            }

                            if (c>rightFloatQty) {
                                break;
                            }
                        }

                        r.height(sourceHeight + "px");
                        rightFloatTable.append(r);
                    }
                });

                var realTableFootRows=$(realTable).children("tfoot").children("tr");

                if (realTableFootRows.length>0) {
                    
                    realTableFootRows.each(function (index, e) {
                    var row = $(e);
                    var tdlst = $(row).children("td");
                    var sourceHeight = $(e).height();

                    if (leftFloatTable) {
                        leftFloatTable.append("<tfoot></tfoot>");
                        var leftFloatFooter = leftFloatTable.children("tfoot");

                        var r = $("<tr></tr>");
                        var c = 0;
                        var i = 0;
                        while (c<leftFloatQty) {
                            r.append($(tdlst[i]).clone(true, true));

                            if ($(tdlst[i]).attr("colspan")) {
                                c += $(tdlst[i]).attr("colspan");
                            } else {
                                c++;
                            }

                            i++;
                        }
                        //for (var i = 0; i < leftFloatQty; i++) {
                            

                        //}
                        r.height(sourceHeight + "px");
                        leftFloatFooter.append(r);
                    }

                    if (rightFloatTable) {
                        rightFloatTable.append("<tfoot></tfoot>");

                        var rightFloatFooter = rightFloatTable.children("tfoot");

                        var r = $("<tr></tr>");
                        var c = 0;
                        var i = 0;

                        for (var i = rightFloatQty - 1; i >= 0; i--) {
                            r.append($(tdlst[tdlst.length - 1 - i]).clone(true, true));

                            if ($($(tdlst[tdlst.length - 1 - i])).attr("colspan")) {
                                c += $($(tdlst[tdlst.length - 1 - i])).attr("colspan");
                            } else {
                                c++;
                            }

                            if (c>rightFloatQty) {
                                break;
                            }
                        }

                        r.height(sourceHeight + "px");
                        rightFloatFooter.append(r);
                    }
                });
                }

                

                $(outSideBoxBody).append("<div class=\"webui_table_float_tablecontent\"></div>");

                outSideBox.insertBefore(realTable);

                $(outSideBoxBody).children(".webui_table_float_tablecontent").append(realTable);

                if (outSideBox) {
                    outSideBox.removeClass("hidden");
                }

                if (leftFloatDiv) {
                    leftFloatDiv.removeClass("hidden");

                    if (leftFloatTableWidth > outSideBoxBody.width()) {
                        leftFloatTableWidth = outSideBoxBody.width();
                    }

                    $(leftFloatTable).width(leftFloatTableWidth);
                }

                if (rightFloatDiv) {
                    rightFloatDiv.removeClass("hidden");

                    if (rightFloatTableWidth > outSideBoxBody.width()) {
                        rightFloatTableWidth = outSideBoxBody.width();
                    }

                    $(rightFloatTable).width(rightFloatTableWidth);
                }

                realTable.addClass("wraped");

                if (endOptions.scrollY && endOptions.scrollHeight > 0) {
                    var scrollWidth = getScrollWidth();
                    var content = $(outSideBoxBody).children(".webui_table_float_tablecontent");

                    content.css("overflow-y", "auto").css("max-height", endOptions.scrollHeight + "px");

                    var floatDivMaxHeight = content[0].scrollWidth > content[0].clientWidth ? (endOptions.scrollHeight - scrollWidth) : endOptions.scrollHeight;

                    if (leftFloatDiv) {
                        leftFloatDiv
                            .css("max-height", floatDivMaxHeight + "px")
                            .css("overflow", "hidden");

                        content.data("leftFloatDiv", leftFloatDiv);
                    }

                    if (rightFloatDiv) {
                        rightFloatDiv
                            .css("max-height", floatDivMaxHeight + "px")
                            .css("right", content[0].scrollHeight > content[0].clientHeight ? scrollWidth : 0)
                            .css("overflow", "hidden");

                        content.data("rightFloatDiv", rightFloatDiv);
                    }

                    content.scroll(__onScrollYHandler);
                }

                outSideBoxBody.find("td .delrow").each(function () {
                    $(this).click(function () {
                        var that = $(this);
                        WebUIJS.Confirm("是否删除该行?", "删除确认", function () {
                            $(that).closest("tr").remove();
                            //.remove();
                            $table.simpleTable().refresh();
                        }
                        );
                    });
                });

                var onSortClick = debounce(200, __onSortByButtonClick);
                outSideBox.find("i.head-sort-icon").click(onSortClick);

                $(realTable).find("th").each(function (index, item) {
                    if ($(item).hasClass("selectcol")) {
                        $(item).find(":checkbox").change(function () {
                            var isChecked = $(this).is(":checked");
                            $(realTable).find("tbody tr").each(function () {
                                var checkbox = $($(this).find("td")[index]).find(".layui-form-checkbox");
                                if (isChecked !== checkbox.is(".layui-form-checked")) {
                                    checkbox.click();
                                }
                            });
                        });
                    }
                });

            }

            $(realTable).find("th.selectcol :checkbox.selectall").change(function () {
                var th = $(this).closest("th");
                var ck = $(this);

                var index = $(realTable).find("thead th").index(th);

                $($(th).closest("table").find('tbody')[0]).find("tr").each(function () {
                    if (ck.is(":checked")) {
                        $(this).find("td:eq(" + index + ") .layui-form-checkbox:not(.layui-form-checked)").click();
                    } else {
                        $(this).find("td:eq(" + index + ") .layui-form-checkbox.layui-form-checked").click();
                    }
                });

                // tbody.find("tr td:eq(" + index + ") .layui-form-checkbox").each(function(){
                //     $(this).click();
                // })
            });

            if (endOptions.autoAddRow) {
                WebUIJS.InitAutoAddTableRow($table, null);
            }

            if (isInitCompleted) {
                $table.trigger("webui_table.refresh", this);
            }

        }


        this.refresh();
        isInitCompleted = true;

        $table.data("webui_table_object", this);
        $table.trigger("webui_table.init", this);

        return this;
    };

    var debounce = function (idle, action) {
        var last
        return function () {
            var ctx = this, args = arguments
            clearTimeout(last)
            last = setTimeout(function () {
                action.apply(ctx, args)
            }, idle)
        }
    }
})(jQuery);

function getScrollWidth() {
    var noScroll, scroll, oDiv = document.createElement("DIV");
    oDiv.style.cssText = "position:absolute; top:-1000px; width:100px; height:100px; overflow:hidden;";
    noScroll = document.body.appendChild(oDiv).clientWidth;
    oDiv.style.overflowY = "scroll";
    scroll = oDiv.clientWidth;
    document.body.removeChild(oDiv);
    return noScroll - scroll;
}